package com.example.weight.wormHandle.cultivate;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class MiddleWormBreedingIncoming extends AppCompatActivity{

    private String primaryKeyText, idStr, goWhereStr, factory;

    private Spinner sp_primary_key, sp_go_where;

    private EditText et_begin_date, et_total_weight, et_net_weight, et_box_number, et_per_box
            , et_per_box_material, et_number, et_middle_worm_breed_box, et_middle_worm_quality
            , et_target, et_fact, et_big_out_date;

    private TextView tv_number;

    private List<String> primaryKeyList, idList, gowhereList;
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private String activeButton = "";
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_middle_worm_breeding_incoming);
        Intent previousIntent = getIntent();
//        name = previousIntent.getStringExtra("name");
//        System.out.println(name);
        factory = previousIntent.getStringExtra("factory");

        //主键
        primaryKeyList = new ArrayList<>();


        idList = new ArrayList<>();

        //去向五选一
        gowhereList = new ArrayList<>();
        gowhereList.add("集装箱");
        gowhereList.add("书柜");
        gowhereList.add("种虫");
        gowhereList.add("项目");
        gowhereList.add("其它");

        //编辑框声明
        et_begin_date = findViewById(R.id.et_begin_date);
        et_total_weight = findViewById(R.id.et_total_weight);
        et_net_weight = findViewById(R.id.et_net_weight);
        et_box_number = findViewById(R.id.et_box_quality);
        et_per_box = findViewById(R.id.et_per_box);
        et_per_box_material = findViewById(R.id.et_per_box_material);
        et_middle_worm_breed_box = findViewById(R.id.et_breed_no);
        et_middle_worm_quality = findViewById(R.id.et_middle_worm_quality);
        et_target = findViewById(R.id.et_target);
        et_fact = findViewById(R.id.et_fact);
        et_big_out_date = findViewById(R.id.et_big_out_date);

        //文本框声明
        tv_number = findViewById(R.id.tv_number);

        //下拉框声明
        sp_primary_key = findViewById(R.id.sp_primary_key);
        sp_go_where = findViewById(R.id.sp_go_where);


        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        getPrimaryKeyRecord();
        et_begin_date.setText(simpleDateFormat.format(new Date()));
        et_begin_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(MiddleWormBreedingIncoming.this, 2, et_begin_date, calendar);
            }
        });

        et_big_out_date.setText(simpleDateFormat.format(new Date()));
        et_big_out_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(MiddleWormBreedingIncoming.this, 2, et_big_out_date, calendar);
            }
        });
    }

    public void submit(View view){
        if (sp_primary_key.getSelectedItem().toString().equals("")) {
            Toast.makeText(this, "请选择批次/组别/孵化盒盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_begin_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写小虫培育开始日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_total_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请获取小虫培育加料重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_net_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请获取小虫培育盒重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_box_number.getText().toString().equals("")) {
            Toast.makeText(this, "请填写小虫培育盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_per_box.getText().toString().equals("")) {
            Toast.makeText(this, "请填写每盒虫及渣", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_per_box_material.getText().toString().equals("")) {
            Toast.makeText(this, "请获取中虫每盒加培育料", Toast.LENGTH_SHORT).show();
            return;
        }
        if(sp_primary_key.getSelectedItem().toString().equals("")) {
            Toast.makeText(this, "请选择大虫去向", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_box_number.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫培育盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_middle_worm_quality.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫数量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_target.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫虫、渣（目标值）", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_fact.getText().toString().equals("")) {
            Toast.makeText(this, "请获取中虫虫、渣（实际值）", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_big_out_date.getText().toString().equals("")) {
            Toast.makeText(this, "请选择大虫出料日期", Toast.LENGTH_SHORT).show();
            return;
        }


        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/smallWormBreedingFeed/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")){
                                            Toast.makeText(MiddleWormBreedingIncoming.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(MiddleWormBreedingIncoming.this, MiddleWormBreedingIncoming.class);
                                            startActivity(intent);
                                            MiddleWormBreedingIncoming.this.finish();
                                        }
                                        else
                                            Toast.makeText(MiddleWormBreedingIncoming.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(MiddleWormBreedingIncoming.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("LB", error.toString());
                        }
                    })
                    {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("factory",factory);
//                            map.put("id", idStr);
//                            map.put("small_bug_breed_time", tv_start_date.getText().toString());
//                            map.put("small_bug_breed_material_weight", et_feed_weight.getText().toString());
//                            map.put("small_bug_breed_box_weight", et_box_weight.getText().toString());
//                            map.put("small_bug_breed_box_number", et_small_worm_box_no.getText().toString());
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void getPrimaryKeyRecord(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url2 = Config.url + "/hsmpy/smallWormBreedingFeed/getlist" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        jsonObject = data.getJSONObject(i);
                                        primaryKeyList.add(jsonObject.getString("batch")+ "/" +jsonObject.getString("wormGroup")+"/"
                                                +jsonObject.getString("hatchBoxNumber"));
                                        idList.add(jsonObject.getString("id"));
                                    }
                                    Log.d("primaryKeyList", primaryKeyList.toString());
                                    ArrayAdapter<String> adapter = new ArrayAdapter<>(MiddleWormBreedingIncoming.this, android.R.layout.simple_spinner_item, primaryKeyList);
                                    ArrayAdapter<String> goWhereAdapter = new ArrayAdapter<>(MiddleWormBreedingIncoming.this, android.R.layout.simple_spinner_item, gowhereList);
                                    sp_primary_key.setAdapter(adapter);
                                    sp_go_where.setAdapter(goWhereAdapter);
                                    sp_primary_key.setSelection(0,true);
                                    sp_go_where.setSelection(0,true);
                                    primaryKeyText = primaryKeyList.get(0);
                                    goWhereStr = gowhereList.get(0);
                                    idStr = idList.get(0);
                                    sp_primary_key.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            primaryKeyText = primaryKeyList.get(position);
                                            idStr = idList.get(position-1);
                                            Toast.makeText(MiddleWormBreedingIncoming.this, primaryKeyText, Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {

                                        }
                                    });
                                    sp_go_where.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            primaryKeyText = primaryKeyList.get(position);
                                            Toast.makeText(MiddleWormBreedingIncoming.this, primaryKeyText, Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {

                                        }
                                    });
                                }else {
                                    Toast.makeText(MiddleWormBreedingIncoming.this, "沒有可操作的數據", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MiddleWormBreedingIncoming.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);
    }

    @SuppressLint("NonConstantResourceId")
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.btn_get_material_weight:
                activeButton = "btn_get_material_weight";
                break;
            case R.id.btn_get_box_weight:
                activeButton = "btn_get_box_weight";
                break;
            default:
                break;
        }
        Intent intent = new Intent(MiddleWormBreedingIncoming.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "btn_get_total_weight":
                et_total_weight.setText(weight);
                break;
            case "btn_get_per_weight":
                et_per_box_material.setText(weight);
                break;
            case "btn_get_fact":
                et_target.setText(weight);
                break;
            default:
                break;
        }
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}

